package com.neusoft.elm.dao.impl;

import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.neusoft.elm.dao.BusinessDao;
import com.neusoft.elm.po.Business;
import com.neusoft.elm.util.DBUtil;

public class BusinessDaoImpl implements BusinessDao {
    private Connection con = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;

    @Override
    public List<Business> listBusinessByOrderTypeId(Integer orderTypeId) throws Exception {
        List<Business> list = new ArrayList<>();
        String sql = "select * from business where orderTypeId=? order by businessId";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1, orderTypeId);
            rs = pst.executeQuery();
            while (rs.next()) {
                Business business = new Business();
                business.setBusinessId(rs.getInt("businessId"));
                business.setBusinessName(rs.getString("businessName"));
                business.setBusinessAddress(rs.getString("businessAddress"));
                business.setBusinessExplain(rs.getString("businessExplain"));
                business.setBusinessImg(rs.getString("businessImg"));
                business.setOrderTypeId(rs.getInt("orderTypeId"));
                business.setStarPrice(rs.getDouble("starPrice"));
                business.setDeliveryPrice(rs.getDouble("deliveryPrice"));
                business.setRemarks(rs.getString("remarks"));
                list.add(business);
            }
        } finally {
            DBUtil.close(rs, pst);
        }
        return list;
    }

    @Override
    public Business getBusinessById(Integer businessId) throws Exception {
        Business business = null;
        String sql = "select * from business where businessId=?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1, businessId);
            rs = pst.executeQuery();
            while (rs.next()) {
                business = new Business();
                business.setBusinessId(rs.getInt("businessId"));
                business.setPassword(rs.getString("password"));
                business.setBusinessName(rs.getString("businessName"));
                business.setBusinessAddress(rs.getString("businessAddress"));
                business.setBusinessExplain(rs.getString("businessExplain"));
                business.setBusinessImg(rs.getString("businessImg"));
                business.setOrderTypeId(rs.getInt("orderTypeId"));
                business.setStarPrice(rs.getDouble("starPrice"));
                business.setDeliveryPrice(rs.getDouble("deliveryPrice"));
                business.setRemarks(rs.getString("remarks"));
            }
        } finally {
            DBUtil.close(rs, pst);
        }
        return business;
    }
    
    @Override
    public int saveBusiness(Business business) throws Exception {
        int generatedId = 0;
        Connection con = null;
        PreparedStatement pst = null;
        ResultSet rs = null;
        
        String sql = "INSERT INTO business (businessName, password, businessAddress, "
                   + "businessExplain, businessImg, orderTypeId, starPrice, deliveryPrice, remarks) "
                   + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        try {
            con = DBUtil.getConnection();
            // 关键修改：指定需要返回生成的主键
            pst = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            
            pst.setString(1, business.getBusinessName());
            pst.setString(2, business.getPassword());
            pst.setString(3, business.getBusinessAddress());
            pst.setString(4, business.getBusinessExplain());
            pst.setString(5, business.getBusinessImg());
            pst.setInt(6, business.getOrderTypeId());
            pst.setDouble(7, business.getStarPrice());
            pst.setDouble(8, business.getDeliveryPrice());
            pst.setString(9, business.getRemarks());
            
            // 执行插入
            int affectedRows = pst.executeUpdate();
            
            if (affectedRows > 0) {
                // 获取生成的主键
                rs = pst.getGeneratedKeys();
                if (rs.next()) {
                    generatedId = rs.getInt(1);
                }
            }
        } finally {
            // 关闭资源
            //DBUtil.close(rs);
            DBUtil.close(pst);
            // 注意：不要关闭连接，因为可能在Service层统一管理
        }
        return generatedId;
    }
    
    @Override
    public Business getBusinessByIdAndPassword(Integer businessId, String password) throws Exception {
        Business business = null;
        String sql = "SELECT * FROM business WHERE businessId = ? AND password = ?";
        try {
            con = DBUtil.getConnection();
            pst = con.prepareStatement(sql);
            pst.setInt(1, businessId);
            pst.setString(2, password);
            rs = pst.executeQuery();
            if (rs.next()) {
                business = new Business();
                // 设置所有字段...
                business.setPassword(rs.getString("password"));
                business.setBusinessId(rs.getInt("businessId"));
                business.setBusinessName(rs.getString("businessName"));
                business.setBusinessAddress(rs.getString("businessAddress"));
                business.setBusinessExplain(rs.getString("businessExplain"));
                business.setBusinessImg(rs.getString("businessImg"));
                business.setOrderTypeId(rs.getInt("orderTypeId"));
                business.setStarPrice(rs.getDouble("starPrice"));
                business.setDeliveryPrice(rs.getDouble("deliveryPrice"));
                business.setRemarks(rs.getString("remarks"));
                // ... 其他字段设置 ...
            }
        } finally {
            DBUtil.close(rs, pst);
        }
        return business;
    }
    
    public int updateBusiness(Business business) throws Exception {
        int result = 0;
        Connection con = null;
        PreparedStatement pst = null;
        
        try {
            con = DBUtil.getConnection();
            // 开启事务
            con.setAutoCommit(false);
            
            String sql = "UPDATE business SET " +
                "businessName = ?, " +
                "password = ?, " +
                "businessAddress = ?, " +
                "businessExplain = ?, " +
                "businessImg = ?, " +
                "orderTypeId = ?, " +
                "starPrice = ?, " +
                "deliveryPrice = ?, " +
                "remarks = ? " +
                "WHERE businessId = ?";
            
            pst = con.prepareStatement(sql);
            pst.setString(1, business.getBusinessName());
            pst.setString(2, business.getPassword());
            pst.setString(3, business.getBusinessAddress());
            pst.setString(4, business.getBusinessExplain());
            pst.setString(5, business.getBusinessImg());
            pst.setInt(6, business.getOrderTypeId());
            pst.setDouble(7, business.getStarPrice());
            pst.setDouble(8, business.getDeliveryPrice());
            pst.setString(9, business.getRemarks());
            pst.setInt(10, business.getBusinessId());
            
            result = pst.executeUpdate();
            
            // 提交事务
            con.commit();
            
            System.out.println("更新商家成功，影响行数: " + result);
        } catch (Exception e) {
            // 回滚事务
            if (con != null) {
                try {
                    con.rollback();
                    System.err.println("事务回滚: " + e.getMessage());
                } catch (SQLException ex) {
                    System.err.println("回滚失败: " + ex.getMessage());
                }
            }
            throw e;
        } finally {
            // 关闭资源
            if (pst != null) {
                try {
                    pst.close();
                } catch (SQLException e) {
                    System.err.println("关闭PreparedStatement失败: " + e.getMessage());
                }
            }
            if (con != null) {
                try {
                    con.setAutoCommit(true); // 恢复自动提交
                    con.close();
                } catch (SQLException e) {
                    System.err.println("关闭Connection失败: " + e.getMessage());
                }
            }
        }
        return result;
    }
}